package com.mikufufu.blog.security.utils;

import com.mikufufu.blog.common.entity.SysUser;
import com.mikufufu.blog.security.exception.AuthException;
import com.mikufufu.blog.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 权限相关工具类
 * 
 */
@Slf4j
public class AuthUtils {

    /**
     * 获取当前认证的用户对象
     * @return SysUser 当前认证的用户对象
     */
    public static SysUser getUser() {
        Authentication authentication = getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new AuthException("user.cannot.get.identity");
        }
        Object principal = authentication.getPrincipal();
        // 假设SysUser实现了UserDetails接口
        if (principal instanceof UserDetails) {
            return (SysUser) principal;
        }
        return null;
    }

    /**
     * 获取当前用户的用户名
     * @return String 当前用户的用户名
     */
    public static String getUsername() {
        SysUser user = getUser();
        if (StringUtils.isEmpty(user)) {
            return "";
//            throw new AuthException("用户对象为空，无法获取用户名");
        }
        return user.getUsername();
    }

    /**
     * 获取当前用户的用户ID
     * @return Integer 当前用户的用户ID
     */
    public static Integer getUserId() {
        SysUser user = getUser();
        if (StringUtils.isEmpty(user)) {
            throw new AuthException("user.cannot.get.userid");
        }
        return user.getUserId();
    }

    /**
     * 获取当前用户的token
     * @return String 当前用户的token
     */
    public static String getToken() {
        Authentication authentication = getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new AuthException("user.cannot.get.identity");
        }
        Object credentials = authentication.getCredentials();
        // 假设credentials是一个字符串
        if (credentials instanceof String) {
            return (String) credentials;
        }
        return null;
    }

    /**
     * 获取当前认证的Authentication对象
     * @return Authentication 当前认证的Authentication对象
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
}
